import { forwardRef, useImperativeHandle, useState } from "react";
import dayjs from "dayjs";
import { Button, DatePicker, Drawer, Form, Input, message, Select } from "antd";
import { getCourse, getTeacherTitle, getGender } from "@/pages/SchoolManage/common/index";
import { addTeacherApi, updateTeacherApi } from "@/api/school/teacher/index";
import type { TableDataType } from "../types/tableCard.type";
import type { FormProps } from "antd";
import type { DrawerType, DrawerRefType } from "../types/editDrawerCard.type";

const { TextArea } = Input;

const EditDrawerCard = forwardRef<DrawerRefType, DrawerType>((props, ref) => {
  const [open, setOpen] = useState(false);
  const [id, setId] = useState<number>();
  const [initialValues, setInitialValues] = useState<Partial<TableDataType>>({ isClassTeacher: false });
  const [messageApi, contextHolder] = message.useMessage();

  const onFinish: FormProps<TableDataType>["onFinish"] = async values => {
    if (values.birthday) values.birthday = dayjs(values.birthday).format("YYYY-MM-DD");
    id
      ? await updateTeacherApi<TableDataType>(id, { ...values, teacherId: initialValues.teacherId! })
      : await addTeacherApi<TableDataType>(values);
    messageApi.success("提交成功");
    setTimeout(() => {
      onClose();
    }, 500);
  };
  // * 暴露给父组件的属性, onOpen 是打开抽屉的方法
  useImperativeHandle(ref, () => ({
    onOpen: (record?: TableDataType) => {
      if (record?.id) {
        setId(record.id);
        setInitialValues(() => ({ ...record, birthday: dayjs(record.birthday) as unknown as string }));
      } else {
        init();
      }
      setOpen(true);
    },
  }));
  const init = () => {
    setId(undefined);
    setInitialValues({});
  };
  const onClose = () => {
    setOpen(false);
    props.onClose();
  };
  
  return (
    <>
      {contextHolder}
      <Drawer
        title={`${id ? "编辑" : "新增"}教师`}
        size="large"
        maskClosable={false}
        destroyOnClose={true}
        onClose={onClose}
        open={open}
      >
        <Form
          name="teacherForm"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          initialValues={initialValues}
          onFinish={onFinish}
        >
          <Form.Item label="教师姓名" name="teacherName" rules={[{ required: true, message: "请输入教师姓名" }]}>
            <Input />
          </Form.Item>
          <Form.Item label="负责课程" name="course" rules={[{ required: true, message: "请选择教师负责课程" }]}>
            <Select options={getCourse()} />
          </Form.Item>
          <Form.Item label="职称" name="teacherTitle" rules={[{ required: true, message: "请选择教师职称" }]}>
            <Select options={getTeacherTitle()} />
          </Form.Item>
          <Form.Item label="性别" name="gender" rules={[{ required: true, message: "请选择教师性别" }]}>
            <Select options={getGender()} />
          </Form.Item>
          <Form.Item
            label="联系电话"
            name="teacherPhone"
            validateDebounce={100}
            rules={[
              {
                required: true,
                message: "请输入教师联系电话",
                validator(_, value) {
                  const regular = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
                  if (regular.test(value)) return Promise.resolve();
                  return Promise.reject(new Error("手机号码格式不正确!"));
                },
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="现居住址" name="currentAddress" rules={[{ required: true, message: "请输入教师现居地址" }]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="身份证号"
            name="idCard"
            validateDebounce={100}
            rules={[
              {
                required: true,
                message: "请输入教师身份证号",
                validator(_, value) {
                  const regular = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                  if (regular.test(value)) return Promise.resolve();
                  return Promise.reject(new Error("身份证号码格式不正确!"));
                },
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="身份证地址"
            name="idCardAddress"
            rules={[{ required: true, message: "请输入教师身份证地址" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="生日" name="birthday" rules={[{ required: true, message: "请选择教师生日" }]}>
            <DatePicker className="w-full" />
          </Form.Item>
          <Form.Item label="简介" name="teacherProfile" rules={[{ required: true, message: "请输入教师简介" }]}>
            <TextArea rows={4} />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
});

export default EditDrawerCard;
